<?php
if(!defined("DNREAD")) exit();

class userapi{
    var $db;
    var $data =
    array(
    'prefix' => 'smf_',
    'table' => '',
    'userid' => 'id_member',
    'forumpath' => 'forum/',
    'cookie'=>'SMFCookie282',
    'cookiehost'=>'.danneo.ru',
    'cookieexp'=>3600,
    'avatarpath' => '/forum/avatars/',
    'avatargalpath' => '/forum/gallery/',
    'setting'=>array(),
    'linkreg' => 'forum/index.php?action=register',
    'linklost' => 'forum/index.php?action=reminder',
    'linkprivmess' => 'forum/index.php?action=pm',
    'linksendmess' => '/forum/index.php?action=pm;sa=send',
    'linkprofile' => '/forum/index.php?action=profile;u='
    );
    var $set =
    array(
    'prefix' => 'all_prefix',
    'forumpath' => 'all_path',
    'cookie'=>'Cookies',
    'cookiehost'=>'Cookies domaine',
    'cookieexp'=>'cookies_expire',
    'avatarpath' => 'avatar_path',
    'linkreg' => 'registr',
    'linklost' => 'rest_pass',
    'linkprivmess' => 'private_message',
    'linksendmess' => 'link_send_mess',
    'linkprofile' => 'your_profile'
    );
    var $usermain =
    array(
    'logged' => 0,
    'userid' => 0,
    'gid' => 0,
    'uname' => '',
    'umail' => '',
    'regdate' => '',
    'lastvisit' => '',
    'icq' => '',
    'msn' => '',
    'www' => '',
    'newmsg' => 0,
    'newmsgnr' => 0,
    'avatar' => ''
    );
    var $userfilter =
    array(
    'login' => array('member_name','login','input'),
    'register' => array('date_registered','registr_date','date'),
    'visit' => array('last_login','last_visit','date'),
    'email' => array('email_address','E-Mail','input'),
    );
    var $groups =
    array();

    function userapi(&$db,$logged = false)
    {
        global $setting,$conf,$group;
        $this->db = &$db;
        if (isset($setting['datainteg']) && !empty($setting['datainteg']) || isset($conf['datainteg']) && !empty($conf['datainteg'])) {
             $data = (isset($conf['datainteg']) && !empty($conf['datainteg'])) ? @unserialize($conf['datainteg']) : @unserialize($setting['datainteg']);
             $n = '';
             foreach ($this->data as $k => $v) {
             	$n[$k] = (isset($data[$k])) ? $data[$k] : $v;
             }
             if(is_array($n)){
                 $this->data = $n;
             }
        }
        if (is_array($group)) {
            foreach ($group as $k => $v){
                if ($v['fid'] > 0) {
                    $this->groups[$v['fid']] = array('gid'=>$v['gid'],'title'=>$v['title']);
                }
           }
        }
        $this->data['table'] = $this->data['prefix'].'members';
        if ($logged) {
            return $this->userarray();
        }
    }

    function avatar($scr, $link = false)
    {
        $avatar = '';
        if ($scr) {
            if (substr($scr,0,4) == 'http') {
                $avatar = ($link) ? '<img src="'.$scr.'">' : $scr;
            } else {
               $avatar = ($link) ? '<img src="'.$this->data['avatarpath'].$scr.'">' : $this->data['avatarpath'].$scr;
            }
        }
        return $avatar;
    }

    function userarray()
    {
        global $group;
        if (isset($_COOKIE[$this->data['cookie']])) {
            $_COOKIE[$this->data['cookie']] = stripslashes($_COOKIE[$this->data['cookie']]);
            if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~',$_COOKIE[$this->data['cookie']]) == 1) {
                list($smf['userid'],$smf['pass']) = @unserialize($_COOKIE[$this->data['cookie']]);
                $smf['userid'] = (!empty($smf['userid']) && strlen($smf['pass']) > 0) ? intval($smf['userid']) : 0;
                if ($smf['userid'] > 0 && strlen($smf['pass']) < 41) {
                    if ($newuser = $this->db->fetchrow($this->db->query("SELECT u.*,b.id_ban FROM ".$this->data['prefix']."members AS u LEFT JOIN ".$this->data['prefix']."ban_items AS b ON (b.id_member = u.id_member) WHERE u.id_member  = '".$smf['userid']."' AND b.id_member IS NULL"))) {
                        if (intval($newuser['id_member']) > 0) {
                            $gid = (isset($this->groups[$newuser['id_group']]['gid']) && intval($this->groups[$newuser['id_group']]['gid']) > 0) ? $this->groups[$newuser['id_group']]['gid'] : 0;
                            $this->usermain = array
                            (
                            'logged'=>1,
                            'userid'=>intval($newuser['id_member']),
                            'gid'=>$gid,
                            'uname'=>$newuser['member_name'],
                            'umail'=>$newuser['email_address'],
                            'regdate'=>$newuser['date_registered'],
                            'lastvisit'=>$newuser['last_login'],
                            'icq'=>$newuser['icq'],
                            'msn'=>$newuser['msn'],
                            'www'=>$newuser['website_url'],
                            'newmsg'=>intval($newuser['new_pm']),
                            'avatar'=>((empty($newuser['avatar'])) ? '' : $this->avatar($newuser['avatar'],true))
                            );
                        }
                    }
                }
            }
        }
    }

    function logout()
    {
        if ($this->usermain['logged'] == 1 && intval($this->usermain['userid']) > 0) {
           $data = serialize(array(0, '', 0));
           setcookie($this->data['cookie'],$data,NEWTIME - $this->data['cookieexp'],'/',$this->data['cookiehost'],0);
           //setcookie($this->data['cookie'],'');
           if (isset($_COOKIE['PHPSESSID'])) {
           	   @setcookie('PHPSESSID', '');

           }
        }
    }

    function checkpwd($passw)
    {
        return (strlen($passw) > 32) ? 0 : 1;
    }

    function checklogin($login)
    {
        return (strlen($login) > 32 || strlen($login) < 3) ? 0 : 1;
    }

    function issetmail($mail)
    {
        return $this->db->numrows($this->db->query("SELECT id_member FROM ".$this->data['prefix']."members WHERE email_address = '".$this->db->escape($mail)."' AND id_member <> ".$this->usermain['userid'].""));
    }

    function addmail($mail)
    {
        $this->db->query("UPDATE ".$this->data['prefix']."members SET email_address = '".$this->db->escape($mail)."' WHERE id_member = ".$this->usermain['userid']."");
    }

    function addurl($url)
    {
        if ($url) {
            $url = (!preg_match('#^http[s]?:\/\/#i',$url)) ? "http://".$url : $url;
            $url = (!preg_match('#^http[s]?\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i',$url)) ? '' : $url;
        } else {
            $url = '';
        }
        return $url;
    }

    function adduse($icq, $www, $msn)
    {
        $this->db->query("UPDATE ".$this->data['prefix']."members SET icq = '".$this->db->escape($icq)."', website_url = '".$this->db->escape($www)."',msn = '".$this->db->escape($msn)."' WHERE id_member = '".$this->usermain['userid']."'");
    }

    function associat($in = false)
    {
        $associat = array();
        if ($in) {
            $inq = $this->db->query("SELECT id_member,member_name,date_registered,avatar,icq,website_url FROM ".$this->data['prefix']."members WHERE id_member IN (".$this->db->escape($in).")");
            while ($item = $this->db->fetchrow($inq)) {
                $associat[$item['id_member']] = array
                (
                'userid' => $item['id_member'],
                'uname' => $item['member_name'],
                'regdate' => $item['date_registered'],
                'avatar' => ((empty($item['avatar'])) ? '' : $this->avatar($item['avatar'],false)),
                'icq' => $item['icq'],
                'www' => $item['website_url']
                );
            }
        }
        return $associat;
    }

    function login($login, $pass)
    {
        if ($this->usermain['logged'] == 0 && intval($this->usermain['userid']) == 0) {
            $newuser = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."members WHERE member_name = '".$this->db->escape($login)."'"));
            $newban = $this->db->fetchrow($this->db->query("SELECT id_ban FROM ".$this->data['prefix']."ban_items WHERE id_member = '".$this->db->escape($newuser['id_member'])."' LIMIT 1"));
            if (intval($newban['id_ban']) > 0) {
                define('THIS_BANNED',1);
            }
            if (intval($newuser['id_member']) > 0 && intval($newban['id_ban']) == 0) {
                $newpass = sha1(strtolower($newuser['member_name']).$pass);
                if ($newpass == $newuser['passwd']) {
                    $printcookie = serialize(array($newuser['id_member'],sha1($newuser['passwd'].$newuser['password_salt']),NEWTIME + $this->data['cookieexp'],0));
                    setcookie($this->data['cookie'], $printcookie, NEWTIME + $this->data['cookieexp'],'/',$this->data['cookiehost']);
                    $gid = (isset($this->groups[$newuser['id_group']]['gid']) && intval($this->groups[$newuser['id_group']]['gid']) > 0) ? $this->groups[$newuser['id_group']]['gid'] : 0;
                    $this->usermain = array
                    (
                    'logged'=>1,
                    'userid'=>intval($newuser['id_member']),
                    'gid'=>$gid,
                    'uname'=>$newuser['member_name'],
                    'umail'=>$newuser['email_address'],
                    'regdate'=>$newuser['date_registered'],
                    'lastvisit'=>$newuser['last_login'],
                    'icq'=>$newuser['icq'],
                    'msn'=>$newuser['msn'],
                    'www'=>$newuser['website_url'],
                    'newmsg'=>intval($newuser['new_pm']),
                    'avatar'=>((empty($newuser['avatar'])) ? '' : $this->avatar($newuser['avatar'],true))
                    );
                }
            }
        }
    }

    function group()
    {
        $associat = array();
        $inq = $this->db->query("SELECT * FROM ".$this->data['prefix']."membergroups");
        while ($item = $this->db->fetchrow($inq)) {
             $associat[$item['id_group']] = $item['group_name'];
        }
        return $associat;
    }

    function userlist($sf, $nu, $p, $sess, $sql)
    {
        global $lang;
        $inq = $this->db->query("SELECT u.*,b.id_ban FROM ".$this->data['prefix']."members AS u LEFT JOIN ".$this->data['prefix']."ban_items AS b ON b.id_member = u.id_member ".str_replace('email_address','u.email_address',$sql)." ORDER BY u.id_member DESC LIMIT $sf,$nu");
        while ($item = $this->db->fetchrow($inq)) {
            $style = (intval($item['id_ban']) > 0) ? 'noactive' : 'work-lite';
            echo '<tr>'
                 .'<td class="'.$style.' center">'
                 .$item['member_name']
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['date_registered'],0)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['last_login'],1)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .'<a href=mailto:'.$item['email_address'].'>'.$item['email_address'].'</a>'
                 .'</td>'
                 .'<td class="'.$style.' center">';
            if ($item['id_member'] > 0) {
                 if (intval($item['id_ban']) > 0) {
                     echo '<a href="user.php?dn=unban&uid='.$item['id_member'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_del'].'" src="template/'.$sess['skin'].'/images/unblock.gif" border="0"></a>';
                 } else {
                     //echo '<a href="user.php?dn=ban&uid='.$item['id_member'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_add'].'" src="template/'.$sess['skin'].'/images/block.gif"></a>'
                       echo '<a href="user.php?dn=edit&uid='.$item['id_member'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_edit'].'" src="template/'.$sess['skin'].'/images/edit.gif"></a>';
                         // .'<a href="user.php?dn=del&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_delet'].'" src="template/'.$sess['skin'].'/images/del.gif"></a>';
                 }
            }
           echo '</td>'
                .'</tr>';
        }
    }

   function userdel($uid)
   {
      //if($uid > 2){
      //    $this->db->query("DELETE FROM ".$this->data['prefix']."users WHERE user_id='$uid'");
      //}
   }

   function bandel($uid)
   {
       //if ($uid > 0) {
       //    $this->db->query("DELETE FROM ".$this->data['prefix']."ban_items WHERE id_member = '$uid'");
       //}
   }

   function banadd($uid)
   {
       //if ($uid > 0) {
       //    if ($this->db->numrows($this->db->query("SELECT ban_id FROM ".$this->data['prefix']."banlist WHERE ban_userid='$uid'")) == 0) {
       //        $this->db->query("INSERT INTO ".$this->data['prefix']."banlist VALUES (NULL,$uid,'',NULL)");
       //    }
       //}
   }

   function useredit($uid)
   {
       global $lang;
       if ($uid > 0) {
           $item = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."members WHERE id_member = '".$uid."'"));
           echo '<table  cellpadding="1" cellspacing="1" class="work">'
                .'<tr><td class="work-title center" colspan="2">'.$lang['edit_user'].' '.$item['member_name'].'</td></tr>'
                .'<tr><td class="work-clip strong center" width="20%">E-Mail :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[mail]" size="50" maxlength="50" type="text" value="'.$item['email_address'].'"> '
                .'</td>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'ICQ :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[icq]" size="50" maxlength="15" type="text" value="'.$item['icq'].'"> '
                .'</td>'
                .'</tr>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'MSN :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[msn]" size="50" maxlength="50" type="text" value="'.$item['msn'].'"> '
                .'</td>'
                .'</tr>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'URL :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[www]" size="50" maxlength="50" type="text" value="'.$item['website_url'].'"> '
                .'</td>'
                .'</tr>';

       }
   }

   function usersave($uid, $edit)
   {
      if ($uid > 0 && is_array($edit)) {
          if (isset($edit['mail']) && !empty($edit['mail']) && $this->db->numrows($this->db->query("SELECT id_member FROM ".$this->data['prefix']."members WHERE email_address = '".$this->db->escape($edit['mail'])."' AND id_member <> $uid")) == 0) {
              $this->db->query("UPDATE ".$this->data['prefix']."members SET email_address = '".$this->db->escape($edit['mail'])."' WHERE id_member = '$uid'");
          }
          if (isset($edit['icq'])) {
               $edit['icq'] = preg_match('/^[0-9]+$/D',$edit['icq']) ? $edit['icq'] : '';
               $this->db->query("UPDATE ".$this->data['prefix']."members SET icq = '".$this->db->escape($edit['icq'])."' WHERE id_member = '$uid'");
           }
           if (isset($edit['www'])) {
               $edit['www'] = preg_match('/^[http]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i',$edit['www']) ? $edit['www'] : '';
               $this->db->query("UPDATE ".$this->data['prefix']."members SET website_url = '".$this->db->escape($edit['www'])."' WHERE id_member = '$uid'");
           }
           if (isset($edit['msn'])) {
              $edit['msn'] = preg_match('/^[A-Za-z0-9_\.\-]+@+[A-Za-z0-9_\w\.\-]+\.+[A-Za-z]{2,4}+$/i',$edit['msn']) ? $edit['msn'] : '';
              $this->db->query("UPDATE ".$this->data['prefix']."members SET msn = '".$this->db->escape($edit['msn'])."' WHERE id_member = '$uid'");
           }
      }
   }

  function messagelast($bs)
  {
      global $api,$lang;
      $re = '';
      $bs['order'] = (isset($bs['order']) && $bs['order'] == 'desc') ? 'desc' : 'asc';
      $inq = $this->db->query("SELECT t.*,m.*,b.* FROM ".$this->data['prefix']."topics AS t
      LEFT JOIN ".$this->data['prefix']."messages AS m ON (m.id_msg = t.id_last_msg)
      LEFT JOIN ".$this->data['prefix']."boards AS b ON (m.id_board = b.id_board)
      ORDER BY m.poster_time ".$bs['order']." LIMIT 0,".$bs['col']);
      if ($this->db->numrows($inq) > 0) {
          $target = (empty($bs['target'])) ? '' : ' target="'.$bs['target'].'"';
          $re.= '<table class="forum" width="100%" cellspacing="0" cellpadding="0">'
                .'<tbody class="forumbody">'
                .'<tr>'
                .'<td class="forumtitle">'.$lang['subject'].'</td>';
          if ($bs['author'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['author'].'</td>';
          }
          if ($bs['date'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['all_data'].'</td>';
          }
          if ($bs['replie'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['comment_total'].'</td>';
          }
          $re.= '</tr>'
                .'</tbody>';
          while ($item = $this->db->fetchrow($inq)) {
              $re.= '<tr>'
                    .'<td class="forumtopic">'
                    .'<a href="/forum/index.php?topic='.$item['id_topic'].'.msg'.$item['id_msg'].'#new">'.$item['subject'].'</a>'
                    .'</td>';
              if ($bs['author'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .$item['poster_name']
                        .'</td>';
              }
              if ($bs['date'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .'<span class="time">'.$api->sitetime($item['poster_time']).'</span>'
                        .'</td>';
              }
              if ($bs['replie'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                    .'<span class="time">'.$item['num_replies'].'</span>'
                    .'</td>';
              }
              $re.= '</tr>';
          }
          $re.= '</table>';
      }
      return $re;
  }
}
?>